{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 变量作用域"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "100\n",
      "hello\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "def foo():\n",
    "    b = 'hello'\n",
    "\n",
    "    # Python中可以在函数内部再定义函数\n",
    "    def bar():\n",
    "        c = True\n",
    "        print(a)\n",
    "        print(b)\n",
    "        print(c)\n",
    "\n",
    "    bar()\n",
    "    # print(c)  # NameError: name 'c' is not defined\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    a = 100\n",
    "    # print(b)  # NameError: name 'b' is not defined\n",
    "    foo()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "200\n",
      "100\n"
     ]
    }
   ],
   "source": [
    "def foo():\n",
    "    a = 200\n",
    "    print(a)  # 200\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    a = 100\n",
    "    foo()\n",
    "    print(a)  # 100"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "torch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
